package com.yanfan.zutai.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

import com.alibaba.fastjson2.JSONObject;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.domain.entity.SysDept;
import com.yanfan.common.core.domain.entity.SysUser;
import com.yanfan.common.utils.DateUtils;
import com.yanfan.common.utils.StringUtils;
import com.yanfan.system.mapper.SysDeptMapper;
import com.yanfan.system.service.ISysUserService;
import com.yanfan.zutai.domain.BEchartType;
import com.yanfan.zutai.domain.vo.BHttpRequest;
import com.yanfan.zutai.mapper.BEchartTypeMapper;
import com.yanfan.zutai.service.IBEchartTypeService;
import com.yanfan.zutai.util.Detect;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.yanfan.common.utils.SecurityUtils.getLoginUser;

/**
 * 图大全Service业务层处理
 *
 * @author ruoyi
 * @date 2023-05-25
 */
@Service
public class BEchartTypeServiceImpl implements IBEchartTypeService {
    @Autowired
    private BEchartTypeMapper bEchartTypeMapper;

    @Resource
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询图大全
     *
     * @param id 图大全主键
     * @return 图大全
     */
    @Override
    public BEchartType selectBEchartTypeById(Long id) {
        return bEchartTypeMapper.selectBEchartTypeById(id);
    }

    /**
     * 查询图大全列表
     *
     * @param bEchartType 图大全
     * @return 图大全
     */
    @Override
    public List<BEchartType> selectBEchartTypeList(BEchartType bEchartType) {
        return bEchartTypeMapper.selectBEchartTypeList(bEchartType);
    }

    /**
     * 新增图大全
     *
     * @param bEchartType 图大全
     * @return 结果
     */
    @Override
    public int insertBEchartType(BEchartType bEchartType) {
        Snowflake snowflake = IdUtil.getSnowflake(6, 2);
        long id = snowflake.nextId();
        bEchartType.setId(id);
        bEchartType.setCreateTime(DateUtils.getNowDate());
        int i = bEchartTypeMapper.insertBEchartType(bEchartType);
        SysUser user = getLoginUser().getUser();
        if (!user.isAdmin() && user.getUserId()!=1) {
                bEchartType.setUserId(user.getUserId());
                bEchartType.setTenantId(user.getDeptId());
                bEchartType.setTenantName(user.getUserName());
               bEchartTypeMapper.addbEchartZtUser(bEchartType);
        }
        return i;
    }

    /**
     * 修改图大全
     *
     * @param bEchartType 图大全
     * @return 结果
     */
    @Override
    public int updateBEchartType(BEchartType bEchartType) {
        bEchartType.setUpdateTime(DateUtils.getNowDate());
        return bEchartTypeMapper.updateBEchartType(bEchartType);
    }

    /**
     * 批量删除图大全
     *
     * @param ids 需要删除的图大全主键
     * @return 结果
     */
    @Override
    public int deleteBEchartTypeByIds(Long[] ids) {
        return bEchartTypeMapper.deleteBEchartTypeByIds(ids);
    }

    /**
     * 删除图大全信息
     *
     * @param id 图大全主键
     * @return 结果
     */
    @Override
    public int deleteBEchartTypeById(Long id) {
        return bEchartTypeMapper.deleteBEchartTypeById(id);
    }

    @Override
    public String sendHttpRequest(BHttpRequest bHttpRequest) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "接口请求异常，请联系相关人员！！！";
        try {
            if ("get".equals(bHttpRequest.getMethod())) {
                // 创建http请求
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                for (int i = 0; i < bHttpRequest.getParams().size(); i++) {
                    if (Detect.notEmpty(bHttpRequest.getParams().get(i).getKey())) {
                        params.add(new BasicNameValuePair(bHttpRequest.getParams().get(i).getKey(), bHttpRequest
                                .getParams()
                                .get(i)
                                .getValue()));
                    }
                }
                URIBuilder builder = new URIBuilder(bHttpRequest.getUrl());
                builder.setParameters(params);
                HttpGet httpGet = new HttpGet(builder.build());
                // 请求类型
                httpGet.addHeader("Content-Type", bHttpRequest.getContentType());
                for (int i = 0; i < bHttpRequest.getHeaders().size(); i++) {
                    if (Detect.notEmpty(bHttpRequest.getHeaders().get(i).getKey())) {
                        httpGet.addHeader(bHttpRequest.getHeaders().get(i).getKey(), bHttpRequest
                                .getHeaders()
                                .get(i)
                                .getValue());
                    }
                }
                // 设置超时时间
                RequestConfig requestConfig = RequestConfig
                        .custom()
                        .setConnectTimeout(3000)
                        .setConnectionRequestTimeout(1000)
                        .setSocketTimeout(3000)
                        .build();
                httpGet.setConfig(requestConfig);
                response = httpClient.execute(httpGet);
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            } else if ("post".equals(bHttpRequest.getMethod())) {
                // 创建http请求
                HttpPost httpPost = new HttpPost(bHttpRequest.getUrl());
                httpPost.addHeader("Content-Type", bHttpRequest.getContentType());
                StringEntity entity = new StringEntity(JSONObject.parse(bHttpRequest.getData()).toString());
                httpPost.setEntity(entity);
                for (int i = 0; i < bHttpRequest.getHeaders().size(); i++) {
                    if (Detect.notEmpty(bHttpRequest.getHeaders().get(i).getKey())) {
                        httpPost.addHeader(bHttpRequest.getHeaders().get(i).getKey(), bHttpRequest
                                .getHeaders()
                                .get(i)
                                .getValue());
                    }
                }
                response = httpClient.execute(httpPost);
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            } else if ("put".equals(bHttpRequest.getMethod())) {
                // 创建http请求
                HttpPut httpPut = new HttpPut(bHttpRequest.getUrl());
                httpPut.addHeader("Content-Type", bHttpRequest.getContentType());
                StringEntity entity = new StringEntity(JSONObject.parse(bHttpRequest.getData()).toString());
                httpPut.setEntity(entity);
                for (int i = 0; i < bHttpRequest.getHeaders().size(); i++) {
                    if (Detect.notEmpty(bHttpRequest.getHeaders().get(i).getKey())) {
                        httpPut.addHeader(bHttpRequest.getHeaders().get(i).getKey(), bHttpRequest
                                .getHeaders()
                                .get(i)
                                .getValue());
                    }
                }
                response = httpClient.execute(httpPut);
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public AjaxResult fpEchartUser(Long deptId, String echartId) {
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
        if (null == sysDept || null == sysDept.getDeptUserId()) {
            return AjaxResult.error("机构不存在或未绑定管理员，请调整后重试！");
        }
        Long deptUserId = sysDept.getDeptUserId();
        SysUser sysUser = userService.selectUserById(deptUserId);
        if (null == sysUser) {
            return AjaxResult.error("机构管理员不存在");
        }
        List<String> echartIdList = StringUtils.str2List(echartId, ",", true, true);
        // 使用 Stream API 将字符串列表转换为长整型列表
        List<Long> echartIdLongList = echartIdList.stream().map(Long::parseLong)  // 将每个字符串转换为 long 类型
                .collect(Collectors.toList());  // 收集结果到列表
        List<BEchartType> bEchartTypes = bEchartTypeMapper.selectEchartZtUserlist(echartIdLongList);
        //获取存在的id数据进行数据修改和
        List<Long> collect = bEchartTypes.stream().map(item -> item.getId()).collect(Collectors.toList());
        List<Long> result = echartIdLongList.stream()
                .filter(id -> !collect.contains(id))
                .collect(Collectors.toList());
        if(result!=null&&result.size()!=0){
            List<BEchartType> bEchartTypes1 = bEchartTypeMapper.selectBEchartTypes(result);
            //新增
            bEchartTypeMapper.bEchartZtUseradd(bEchartTypes1,deptId, sysUser.getUserName(),sysUser.getUserId());
        }
        if(collect!=null && collect.size()!=0){
            //修改
            bEchartTypeMapper.updateEchartUserlist(deptId, sysUser.getUserName(), collect);
        }
        return AjaxResult.success("分配图表成功");
    }


}
